//
//  WmcTeamCloudAlbumManagementVC.swift
//  YPWatermarkCamera
//
//  Created by 赵洋 on 2022/9/8.
//

import UIKit

// MARK: - 扩展WmcTeamCloudAlbumManagementVC + WmcVMProtocol

extension WmcTeamCloudAlbumManagementVC: WmcVMProtocol {
    typealias VMType = WmcTeamCloudAlbumManagementVM
}

// MARK: - [WmcTeamCloudAlbumManagementVC]

class WmcTeamCloudAlbumManagementVC: WmcBaseVC, WmcStatefulViewController {
    // Lifecycle

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        setupInitialViewState()
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        /// 获取团队信息
        viewModel.getTeamInfo()
        setupPlaceholders()

        WmcNotificationManager.shared.addObserver(type: .editTeamNameSucceed) { [weak self] _ in
            guard let weakSelf = self else { return }
            weakSelf.viewModel.getTeamInfo()
        }
    }

    /// 设置占位视图
    /// - Returns: description
    func setupPlaceholders() {
        loadingView = WmcLoadingView()
        // emptyView = self.currentEmptyView
        let errView = WmcErrorView()
        errView.refreshClosure = { [weak self] in
            guard let weakSelf = self else { return }
            weakSelf.viewModel.getTeamInfo()
        }
        errorView = errView
    }

    // Internal

    override func makeUI() {
        makeNavView(style: .white, showShadow: false)
        title = viewModel.title
        /// 导航栏加细线
        navView.addSubview(naviLineView)
        naviLineView.snp.makeConstraints { make in
            make.left.right.bottom.equalToSuperview()
            make.height.equalTo(1)
        }

        view.addSubview(lineView)
        view.addSubview(teamNameView)
        view.addSubview(teamIdView)
        view.addSubview(synSwitch)
        view.addSubview(quitTeamView)

        lineView.snp.makeConstraints { make in
            make.top.equalTo(navView.snp.bottom)
            make.left.right.equalToSuperview()
            make.height.equalTo(1)
        }

        teamNameView.snp.makeConstraints { make in
            make.top.equalTo(lineView.snp.bottom)
            make.left.right.equalToSuperview()
        }

        teamIdView.snp.makeConstraints { make in
            make.top.equalTo(teamNameView.snp.bottom)
            make.left.right.equalToSuperview()
        }

        synSwitch.snp.makeConstraints { make in
            make.top.equalTo(teamIdView.snp.bottom)
            make.left.right.equalToSuperview()
        }

        quitTeamView.snp.makeConstraints { make in
            make.top.equalTo(synSwitch.snp.bottom)
            make.left.right.equalToSuperview()
        }

        synSwitch.switchView.isOn = false
    }

    override func bindViewModel() {
        startLoading()
        viewModel.teamInfo.bind { [weak self] teamInfo in
            guard let weakSelf = self, let team = teamInfo, let album = weakSelf.viewModel.teamAblum else { return }
            weakSelf.teamNameView.note = team.teamName
            weakSelf.teamIdView.teamId = team.teamOpenId
            weakSelf.synSwitch.isSyn = album.isSync ? 1 : 0
            weakSelf.endLoading()
        }.disposed(by: rx.disposeBag)

        viewModel.error.bind { [weak self] error in
            guard let weakSelf = self else { return }
            weakSelf.endLoading(animated: true, error: error, completion: nil)
        }.disposed(by: rx.disposeBag)

        /// 是自己创建的不显示 退出按钮
        viewModel.isTeamCreatedBySelf().bind(to: quitTeamView.rx.isHidden).disposed(by: rx.disposeBag)

        // 是否可编辑团队名称
        WmcAuthManager.share.teamAblum = viewModel.teamAblum
        WmcAuthManager.share.getSelfMember { [weak self] selfMember in
            guard let weakSelf = self else { return }
            weakSelf.teamNameView.hiddenArrow(isHidden: selfMember.role == .member)
        }
    }

    override func bindViewAction() {
        let tap = UITapGestureRecognizer(target: self, action: #selector(tapAction))
        teamNameView.addGestureRecognizer(tap)

        teamIdView.copyBtn.rx.controlEvent(.touchUpInside).bind { [weak self] _ in
            guard let weakSelf = self else { return }
            weakSelf.viewModel.copyTeamId()
        }.disposed(by: rx.disposeBag)

        quitTeamView.deleteBtn.rx.controlEvent(.touchUpInside).bind { [weak self] _ in
            guard let weakSelf = self else { return }
            WmcQuitTeamAlertView.alertView(title: "确定退出团队吗？", content: "退出后将无法查看同步到团队的照片", leftBtnTitle: "取消", rightBtnTitle: "确定", confirmB: {
                weakSelf.viewModel.quitTeam {
                    WmcNotificationManager.shared.post(type: .memberQuitTeam, object: nil)
                }
            }).show()

        }.disposed(by: rx.disposeBag)

        /// 设置同步状态
        synSwitch.coverButton.rx.controlEvent(.touchUpInside).bind { [weak self] _ in
            guard let weakSelf = self else { return }
            if weakSelf.synSwitch.switchView.isOn {
                WmcTeamAlbumSynAlertView.alertView(title: "关闭后，拍摄照片/视频将无法自动同步到相册中", leftBtnTitle: "再想想", rightBtnTitle: "确认关闭", confirmB: {
                    weakSelf.viewModel.updateSynConfig(isSyn: false) { isSyn in
                        weakSelf.synSwitch.switchView.isOn = isSyn
                    }
                }).show()

            } else {
                weakSelf.viewModel.updateSynConfig(isSyn: true) { isSyn in
                    weakSelf.synSwitch.switchView.isOn = isSyn
                    weakSelf.viewModel.teamAblum?.isSync = isSyn
                }
            }
        }.disposed(by: rx.disposeBag)
    }

    @objc func tapAction() {
        let vm = WmcCreateTeamVM()
        vm.opType = .modify
        vm.teamAblum = viewModel.teamAblum
        WmcNavigatorManager.push(.createTeamAlbum, parms: vm)?.hidesBottomBarWhenPushed = true
    }

    lazy var lineView: UIView = {
        let view = UIView()
        view.backgroundColor = UIColor.wmc_grayH19_F5F5F5
        return view
    }()

    lazy var teamNameView: WmcEditTeamMemberInfoNoteItemView = {
        let view = WmcEditTeamMemberInfoNoteItemView()
        view.leftTitle = "团队名称"
        view.note = ""
        return view
    }()

    lazy var teamIdView: WmcTeamManagementTeamIdItemView = {
        let view = WmcTeamManagementTeamIdItemView()
        view.leftTitle = "团队号"
        view.teamId = ""
        return view
    }()

    lazy var synSwitch: WmcTeamManagementSwitchItemView = {
        let view = WmcTeamManagementSwitchItemView()
        view.leftTitle = "拍照自动同步到团队"
        view.isSyn = 1
        return view
    }()

    lazy var quitTeamView: WmcEditTeamMemberInfoDeleteItemView = {
        let view = WmcEditTeamMemberInfoDeleteItemView()
        view.text = "退出团队"
        return view
    }()
}

extension WmcTeamCloudAlbumManagementVC {
    func hasContent() -> Bool {
        guard let _ = viewModel.teamInfo.value else {
            return false
        }
        return true
    }

    func handleErrorWhenContentAvailable(_: Error) {
        /// 处理错误
    }
}
